import axios from 'axios' // 引入
import { showToast,showFailToast } from 'vant'
import { isMobile } from '/src/utils/mobile.js'
import { ElMessage } from 'element-plus'

const service = axios.create({
	//baseURL:'http://1.12.224.118:8082/',
	baseURL:'http://localhost:8082/',
	timeout:60000
})

let hash = location.hash.split('/').splice(1,1)[0]
const removeToken = (hash)=>{
	switch(hash){
		case 'home':
			localStorage.removeItem('user_token');
			break;
		case 'admin':
			localStorage.removeItem('admin_token');
			break;
		case 'enterprise':
			localStorage.removeItem('enterprise_token');
			break;
		default:
			console.log('404页面')
	}
	//刷新页面
	history.go(0)
}

service.interceptors.response.use(
    response => {
		// console.log(response)
        if (response.status && response.status === 200) {
			switch(response.data.code){
				case 403:
					showFailToast('权限不足!');
					break;
				case 401:
					showFailToast('身份验证已过期，请求重新登录!')
					setTimeout(()=>{removeToken(hash)},200)
					break;
				case 500:
					showFailToast(response.data.message);
					break;
				case 400:
					showFailToast(response.data.message);
					break;
				default:
					if(response.data.message){
						showFailToast(response.data.message)
					}
			}
        } 
		return response.data
    },error => {
		if (error.response.status === 504 || error.response.status === 404) {
			showFailToast('服务器被吃了！')
        } else {
			if (error.response.data.message) {
				showFailToast(error.response.data.message)
			} else {
				showFailToast('未知错误')
			}
        }
    }
);

export default service